import http from '../../utils/http';
import { store } from '../../store/index';
import { collect } from "../../API/collect";
import type { getStudyDataType } from "../../../typings/InterfaceData";
import { deconstructEvent } from '../../hooks/deconstructEvent';
const app = getApp<IAppOption>();

Page({
  $data: ['isLogin'],
  data: {
    AddressShow: false,
    area_data: {},
    country_data: {},
    country_title: {},
    headerCustomStyle: false, //  顶部样式
    countrydatas: [],
    school_data: [],
    active: 0,
    scl_category_data: [],
    scl_active: -1,
    mj_category_data: [],
    title_data: {},
    major_data:[]
  },
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0,
      });
    }
  },
  onLoad() {
    let sessionid = wx.getStorageSync('sessionid');
    if (!sessionid) {
      wx.navigateTo({
        url: '/pages/login/login',
      });
    } else {
      this.get_index();
      this.get_area();

    }
    app.watch(this, {
      $isLogin: function (newVal) {
        if (newVal) {
          this.get_index();
          this.get_area();
        }
      },
    });


  },

  //  获取首页默认数据
  get_index() {
    http.get('/get/index/').then((res) => {
      // console.log(res);
      this.setData({
        area_data: res.area_data,
        country_data: res.country_data,
        country_title: res.country_title,
      });
      this.getSchoolList();
      this.getTitle()

    });
  },
  //  获取地区数据
  get_area() {
    http.get('/get/area/').then((res) => {
      // console.log(res,"地区")
      let countrydatas = res.area_data.map((v) => {
        // console.log(v);
        v.text = v.area_name;
        v.value = v.area_id;
        v.children = [];
        v.loaded = false;
        return v;
      });
      this.setData({
        countrydatas,
      })
      // console.log(this.data.countrydatas,"countrydatas");

    }).catch(v => {
      console.log(v)
    })
  },
  //  获取国家数据
  get_country(area_id, index) {
    http
      .get('/get/country/', {
        area_id,
      })
      .then((res) => {
        // console.log(res);
        let countrydatas = this.data.countrydatas;
        // console.log(countrydatas);

        let data = res.country_data.map((v) => {
          v.text = v.country_name;
          v.value = v.country_id;

          return v;
        });
        // console.log(data);
        let key1 = 'countrydatas[' + index + '].children';
        let key2 = 'countrydatas[' + index + '].loaded';

        // console.log(key1);
        this.setData({
          [key1]: data,
          [key2]: true,
        });
      });
  },
  //  显示地址选择框
  showAddressPopup() {
    this.setData({
      AddressShow: true,
    });
  },
  //onAddressPopupClose
  onAddressPopupClose() {
    this.setData({
      AddressShow: false,
    });
  },
  //  选择地址  一级选择
  onchange(e: any) {
    // console.log(e);

    let { selectedOptions } = e.detail;
    let value = selectedOptions[0].area_id
    let countrydatas = this.data.countrydatas;
    let activeAreaIndex = countrydatas.findIndex((v) => {
      return v.area_id === value;
    });
    // console.log(countrydatas)
    if (countrydatas[activeAreaIndex].loaded) return;

    this.get_country(value, activeAreaIndex);
  },
  // 选择地址  最终
  onFinish(e: any) {
    console.log(e)
    let { selectedOptions, tabIndex } = e.detail;

    this.setData({
      country_data: selectedOptions[tabIndex],
    });
    console.log(this.data.country_data)

    this.onAddressPopupClose();
    this.getSchoolList();

  },
  onPageScroll(e) {
    this.setData({
      headerCustomStyle: e.scrollTop > 20,
    });
  },
  onNavChange(e) {
    // console.log(e);
    this.setData({
      active: e.detail.index,
    });
  },

  // /get/school/list/
  getSchoolList() {
    const { country_data } = this.data;
    const { country_id: nid } = country_data

    http.get('/get/school/list/', {
      nid
    }).then((res) => {
      console.log(res, "WEEEEEEEEEEEEEEEEEE");
      const { school_data, scl_category_data } = res;
      this.setData({
        school_data,
        scl_category_data
      });

      this.getMajorList()
    });
  },

  // tabShow( e) {
  //   if (e.detail.title === "专业库") {
  //     this.getMajorList()
  //   } else if (e.detail.title === "院校库") {
  //     this.getSchoolList()
  //   }

  // },

  getMajorList() {
    const { country_data, scl_active, scl_category_data } = this.data;

    let mid = scl_active < 0 ? '' : scl_category_data[scl_active].scl_category_id
    const { country_id: nid } = country_data
    http.get("/get/major/list/", {
      mid,
      nid
    }).then((res) => {
      console.log(res,":::::::::::::::::::::::::::");
      this.setData({
        mj_category_data: res.mj_category_data
      })
    })
  },


  collectSchool(e: Event) {
    const { target } = e
    const { dataset } = target
    const { schoolid, type, index, is_collect } = dataset

    if (is_collect) {
      console.log("取消收藏成功");
      
      http.post("/cancle/collect/", {
        type,
        nid: schoolid
      }).then(res => {
        if (res.success) {
          wx.showToast({
            title: '取消收藏成功',
            icon: "none"
          })
          this.getSchoolList()
        } else {
          wx.showToast({
            title: res.message,
            icon: "error"
          })
          
        }
      })
      return
    }
    collect(type, schoolid).then((res) => {
      console.log("收藏成功");
      
      console.log(res);
      if (res.success) {
        wx.showToast({
          title: '收藏成功',
          icon: "none"
        })
        this.getSchoolList()
        return
      } else {
        wx.showToast({
          title: res.message,
          icon: "error"
        })
      }
    })
  },
  // /get/study/
  getStudy(e: Event) {
    const { country_data } = this.data
    const { country_id: nid } = country_data

    const { nav_type: type, url } = deconstructEvent(e)

    http.get("/get/study/", {
      type,
      nid
    }).then((res) => {
      // console.log(res);
      const { data } = res as getStudyDataType;
      const query: String = JSON.stringify(data)
      wx.navigateTo({
        url: url + "?" + "data=" + encodeURIComponent(query)
      })
    })
  },
  // changeScl  改变专业分类
  changeScl(e) {

    let index = e.currentTarget.dataset.index;
    this.setData({
      scl_active: index
    })

    this.getMajorList()

  },

  // get/school/
  getSchoolDetails(e) {

    const { shcoolid: nid, url, type } = deconstructEvent(e)

    wx.navigateTo({
      url: url + '?nid=' + nid + '&type=' + type
    })



  },

  getTitle() {
    const { country_data } = this.data
    const { country_id: nid } = country_data

    console.log(this.data.country_data);

    http.get("/get/study/", {
      nid
    }).then((res) => {
      console.log(res);
      this.setData({
        title_data: res.title_data
      })
    })
  },

});
